package com.ocom.wxapi.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.UnitsPageOnShowDto;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.RefreshRecentCompanyRequest;
import com.ocom.common.request.company.companyrole.GetRoleUserRequest;
import com.ocom.common.request.wx.CommonRequest;
import com.ocom.common.request.wx.CommonRoleRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.wx.MainPageOnshowResponse;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.wxapi.client.AccessClientService;
import com.ocom.wxapi.client.CompanyClientService;
import com.ocom.wxapi.service.MainPageService;
import com.ocom.wxapi.vo.YkmSumListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@PreAuthorize("hasRole('ROLE_WX')")
@RequestMapping("/MainPage")
@RestController
@Slf4j
public class MainPageController {

    @Autowired
    CompanyClientService companyClientService;

    @Autowired
    AccessClientService accessClientService;

    @Autowired
    MainPageService mainPageService;

    /**
     * 管理（MainPage）
     * 2.8.1 显示页面（MainPage/onShow）
     * */
    @PostMapping("/onShow")
    public Result onShow(@Valid CommonRequest request){

        MainPageOnshowResponse mainPageOnshowResponse=new MainPageOnshowResponse();

        Map<String,Object> map =new HashMap<>();
        map.put("pageTitle","管理+");
        map.put("lbl1Caption","账号信息");
        map.put("lbl3Caption","用户管理");
        map.put("lbl101Caption","开门权限");
        map.put("lbl102Caption","门禁设备");
        map.put("lbl103Caption","门禁记录");
        mainPageOnshowResponse.setPageFormat(map);


        //1.companyName、endDate
        Result result=companyClientService.getCompanyInfoById(request.getCompanyId());
        if(result.getCode()==200){
            EntityCompanyInfo entityCompanyInfo=JSON.parseObject(JSON.toJSONString(result.getData()), EntityCompanyInfo.class);
        //    System.out.println(entityCompanyInfo);
            mainPageOnshowResponse.setCompanyName(entityCompanyInfo.getComName());
            mainPageOnshowResponse.setEndDate(entityCompanyInfo.getEndTime());
            if(entityCompanyInfo.getEndTime().compareTo(new Date())<0){
                mainPageOnshowResponse.setDateColor("red");
            }
        }

        //2.     doorMachNum
        // lisence TODO

        Result result1=accessClientService.getCountByComId(request.getCompanyId());
        if(result.getCode()==200){
            mainPageOnshowResponse.setDoorMachNum(Integer.parseInt(String.valueOf(result1.getData())));
        }
        return ResultUtil.success(mainPageOnshowResponse);


    }


    /**
     * 防疫信息页面（MainPage/onYKMShow）
     * */
    @GetMapping("/onYKMShow")
    public Result onYKMShow(Long comId,Long deptId){
        if (StringUtils.isNull(comId)){
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203,"单位编号为空");
        }

        return mainPageService.onYKMShow(comId,deptId);
    }

    /**
     * 防疫汇总指标列表（MainPage/onYkmSum）
     * */
    @PostMapping("/onYkmSum")
    public Result onYkmSum(@Valid YkmSumListVo ykmSumListVo){
        return mainPageService.onYkmSum(ykmSumListVo);
    }


    /**
     * 2.8.3 显示页面（MainPage/onShow2）
     */
    @PostMapping("/onShow2")
    public Result onShow2(@Valid CommonRoleRequest request){

        CompanyListInfoVo companyListInfoVo = new CompanyListInfoVo();
        companyListInfoVo.setComId(request.getCompanyId());
        companyListInfoVo.setPage(-1);
        companyListInfoVo.setSize(-1);

        if(ObjectUtil.isNotEmpty(request.getAdminId()) && request.getAdminId() > 0){
            RefreshRecentCompanyRequest recentCompanyRequest = new RefreshRecentCompanyRequest();
            recentCompanyRequest.setCompanyId(request.getCompanyId());
            recentCompanyRequest.setAdminId(request.getAdminId());
            recentCompanyRequest.setUserId(request.getPId());
            this.companyClientService.refreshRecentCompany(recentCompanyRequest);
        }
        Result result = companyClientService.GetCompanyListInfo(companyListInfoVo);
        String comName="";
        JSONArray menuTree=null;
        if(result.getCode() == 200){
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
            JSONArray list = jsonObject.getJSONArray("list");
            for (Object object : list) {
                UnitsPageOnShowDto unitsPageOnShowDto = JSON.parseObject(JSON.toJSONString(object), UnitsPageOnShowDto.class);
                comName = unitsPageOnShowDto.getComName();
                Long saasId = unitsPageOnShowDto.getSaasId();
                Integer xfStatus = unitsPageOnShowDto.getXfStatus();
                Integer mjStatus = unitsPageOnShowDto.getMjStatus();
                GetRoleUserRequest getRoleUserRequest = new GetRoleUserRequest();
                getRoleUserRequest.setSaasNo(Math.toIntExact(saasId));
                getRoleUserRequest.setMjVer(mjStatus);
                getRoleUserRequest.setXfVer(xfStatus);
                getRoleUserRequest.setRole(request.getRole());
                Result appMenuByRole = companyClientService.getAppMenuByRole(getRoleUserRequest);
                if(appMenuByRole.getCode() == 200){
                    JSONObject parseObject = JSON.parseObject(JSON.toJSONString(appMenuByRole.getData()));
                     menuTree = parseObject.getJSONArray("menuTree");
                }
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("companyName",comName);
        map.put("menuTree",menuTree);
        return ResultUtil.success(map);
    }

}
